<?php

namespace app\shop\controller;
use app\common\util\ImageUpload;
use think\Controller;

class Order extends Controller
{
    //构造函数
    public function __construct()
    {
        parent::__construct();
        //加载模型
        $this->userModel = model('common/User/User');
        $this->bannerModel = model('common/User/Banner');
        $this->shopModel = model('common/User/Shop');
        $this->cartModel = model('common/User/Cart');
        $this->orderModel = model('common/User/Order');
        $this->orderProductModel = model('common/User/OrderProduct');
        $this->addressModel = model('common/User/Address');
        $this->couponReceiveModel = model('common/User/CouponReceive');
        $this->couponModel = model('common/User/Coupon');
        // 退货
        $this->depotBackModel = model('common/User/DepotBack');
        $this->depotBackProductModel = model('common/User/DepotBackProduct');

    }


    // 查询订单列表 -分类
    public function getOrders(){
      if($this->request->isPost()){
        $uid = (int)$this->request->param('uid');
        $status =$this->request->param('status','0');
        // halt($status);
        // 0、全部；1:已支付；2:已发货；3:已收货；-1:退货；-2:未支付
        // 如果=0则查全部
        if($status == '0'){
          $where = [
          'busid' => $uid
          ];
          $getPrdOrdersRes = $this->orderModel->where($where)->order('id','desc')->select();
        }else{
          $where = [
          'busid' => $uid,
          'status' => $status
          ];
          $getPrdOrdersRes = $this->orderModel->where($where)->order('id','desc')->select();
        }
        // halt($status);
        foreach($getPrdOrdersRes as $item){
          $item['productList'] = (object)$this->orderProductModel->where('orderid',$item['id'])->with(['goodsList'])->select();
        }
        // halt($getOrdersRes);
        $this->success('订单列表查询成功',null,$getPrdOrdersRes);
        exit;
      }
    }

    // 订单详情
    public function getOrderInfo(){
      if($this->request->isPost()){
        $uid = (int)$this->request->param('uid');
        $orderId = (int)$this->request->param('orderId');
        // halt($uid);
        $isUser = $this->userModel->where('id',$uid)->select();
        if($isUser){
          $orderProducts = $this->orderProductModel->where('orderid',$orderId)->with(['goodsList','ordersList'])->select();
          foreach($orderProducts as $item){
            $addressId = $item['orders_list']['businessaddrid'];
          }
          // $orderProducts['address'] = $this->addressModel->where('id',$addressId)->find();
          // halt($orderProducts);
          $address = $this->addressModel->where('id',$addressId)->find();
          $orderData = [
            'orderProducts'=>$orderProducts,
            'addressData' => $address,
          ];
          // halt($this->addressModel->where('id',$addressId)->find());
          $this->success('订单商品详情数据返回成功',null,$orderData);
          exit;
          // halt($orderProducts);
        }
      }
    }

    // 订单未支付，进行支付
    public function goPayOrder(){
      if($this->request->isPost()){
        // halt(111);
        $uid = (int)$this->request->param('uid');
        $orderid = $this->request->param('orderid');
        $status = $this->request->param('status');

        // 查一下该订单是不是和传过来的值一样是未支付状态
        $isStatus = $this->orderModel->where('id',$orderid)->value('status');
        $isUser = $this->orderModel->where('id',$orderid)->value('busid');
        // halt($isStatus);
        // 如果前端传过来的状态值和订单一样
        if($isStatus == $status && $uid==$isUser){
          // 获取订单商品总价格
          $orderPrice =  (int)$this->orderModel->where('id',$orderid)->value('amount');
          // 获取用户账户的钱
          $userMoney =  $this->userModel->where('id',$uid)->value('money');
          // halt($userMoney);
          if($userMoney >= $orderPrice){
            // 立即支付-开启事务
            /**
             * startTrans rollback commit
             * 1.更改用户账户的余额
             * 2.更新订单的状态
             */
            $this->userModel->startTrans();
            $this->orderModel->startTrans();
            
            $updateMoney = $userMoney-$orderPrice;
            // halt($updateMoney);
            $updMoney = [
              'money'=>$updateMoney,
            ];
            // 更新用户余额
            $updateUMoney = $this->userModel->where('id',$uid)->update($updMoney);

            if($updateUMoney ===FALSE){
              $this->error('支付失败',null);
              exit;
            }
            // 更新订单状态
            $updOrderStatus = $this->orderModel->where('id',$orderid)->update(['status'=>1]);
            if($updOrderStatus === FALSE){
              $this->userModel->rollback();
              $this->error('更新订单状态失败');
              exit;
            }

            if($updateUMoney === FALSE || $updOrderStatus === FALSE){
              $this->orderModel->rollback();
              $this->userModel->rollback();
              $this->error('支付失败');
              exit;
            }else{
              $this->userModel->commit();
              $this->orderModel->commit();
              $this->success('支付成功');
              exit;
            }
            // halt( $updateUMoney);
          }
          // halt(111);
          // $pay = $this->userModel
        }else{
          $this->error('非法操作,无法进行支付');
          exit;
        }
      }
    }

    // 确认收货 confirmReceipt
    public function confirmReceipt(){
      if($this->request->isPost()){
        // halt(111);
        $uid = (int)$this->request->param('uid');
        $orderid = $this->request->param('orderid');
        $status = $this->request->param('status');

        $isStatus = $this->orderModel->where('id',$orderid)->value('status');
        $isUser = $this->orderModel->where('id',$orderid)->value('busid');
        // halt($isStatus);
        // 如果前端传过来的状态值和订单一样
        if($isStatus == $status && $uid==$isUser){
          // halt(222);
          // 直接更新订单状态-为确认收货
          $updOrderStatus = $this->orderModel->where('id',$orderid)->update(['status'=>3]);
          $this->success('订单已确认收货',null);
          exit;
        }else{
          $this->error('非法操作,无法进行支付');
          exit;
        }
        

      }
    }

    // 申请退货 returnOrder
    public function refund(){
      if($this->request->isPost()){
        // halt(111);
        $selectedReason = $this->request->param('selectedReason');
        $refundReason = $this->request->param('refundReason');
        $fileList = json_decode($this->request->param('fileList'));
        // 上传文件的对象
        $imageObjects = json_decode($this->request->param('fimg'));
        // halt($imageObjects);
        $uid = $this->request->param('uid');
        $orderCode = $this->request->param('orderCode');
        $status = $this->request->param('status');
        
        // 查询是否有该用户
        $isUser = $this->userModel->where('id',$uid)->find();

        // 查询订单编号
        $orderRes = $this->orderModel->where('code',$orderCode)->find();
        // 程序该订单的用户
        $orderUId = $this->orderModel->where('code',$orderCode)->value('busid');

        // 判断是否为合法用户
        if($isUser && $uid==$orderUId && $orderRes){
          // 上传多个图片并生成缩略图
          $result = ImageUpload::uploadMultiple(
              $imageObjects, 
              'uploads/products/', 
              ['jpg', 'jpeg', 'png', 'gif'], 
              5242880, // 5MB
              false // 不生成缩略图
          );
          // 存放图片url组
          $data = [];
          foreach($result["success"] as $item){
            $data[] = $item["data"]["file_path"];
            // halt($item);
          }
          // 储存退货图集
          $imgs = implode(',', $data);
          // halt($imgs);

          // halt(11);
          // 存储退货数据
          $refundData = [
            'code'=> build_code('RF-'),
            'ordercode'=> $orderCode,
            'busid' => $uid,
          ];
          // 获取订单的地址表外键
          $businessaddrid = $this->orderModel->where('code',$orderCode)->value('businessaddrid');
          // halt($businessaddrid);
          // 查询地址表的数据
          $addressData = $this->addressModel->where('id',$businessaddrid)->find();
          $refundData['contact'] = $addressData['name'];
          $refundData['phone'] = $addressData['tel'];
          $refundData['address'] = $addressData['address'];
          $refundData['province'] = $addressData['province'];
          $refundData['city'] = $addressData['city'];
          $refundData['district'] = $addressData['district'];
          $amount = $this->orderModel->where('code',$orderCode)->value('amount');
          $refundData['amount'] = $amount;
          $refundData['remark'] = $refundReason;
          // 刚申请，先设置为已审核 
          $refundData['status'] = 1;
          $refundData['refundreason'] = $selectedReason;
          $refundData['thumbs'] = $imgs;

          // 先查看有没有该订单号，有则无法再新增
          $isorder = $this->depotBackModel->where('ordercode',$orderCode)->select();
          $orderid = $this->orderModel->where('code',$orderCode)->value('id');
          // halt($orderid);
            if(!$isorder){
              // 开启事务
              /**
               * 1.先增加退货单
               * 2.修改订单状态
               * 3.增加退货商品表
               * 4.修改商品库存
               * 5.修改用户的账户余额
               * 6.若有用优惠券，判断是否过了活动期限，是则不返回，否则返回
               * 
               **/
              $this->depotBackModel->startTrans();
              $this->orderModel->startTrans();
              $this->depotBackProductModel->startTrans();
              $this->shopModel->startTrans();
              $this->userModel->startTrans();
              $this->couponReceiveModel->startTrans();
              // 1.先增加退货单
              $refundRes = $this->depotBackModel->save($refundData);
              if($refundRes === FALSE){
                $this->error('申请退货失败');
                exit;
              }

              // 2.修改订单状态
              $updataSta = [
                'id'=>$orderid,
                'status'=>-1
              ];
              $updateOStatusRes = $this->orderModel->isUpdate(true)->save($updataSta);
              if($updateOStatusRes===FALSE){
                $this->depotBackModel->rollback();
                $this->error('修改订单状态失败');
                exit;
              }

              // 3.增加退货商品表
              $proData = $this->orderProductModel->where('orderid',$orderid)->select();
              $count = count($proData);
              // halt($count);
              $result = [];
              $pids = [];
              $nums = [];
              for ($i=0; $i < $count ; $i++) { 
                $result[] = [
                    'backid'=>$this->depotBackModel->id,
                    'proid'=>$proData[$i]['proid'],
                    'nums'=>$proData[$i]['pronum'],
                    'price'=>$proData[$i]['price'],
                    'total'=>$proData[$i]['total'],
                ];
                $pids[] = $proData[$i]['proid'];
                $nums[] = $proData[$i]['pronum'];
              }
              $depotBackProRes = $this->depotBackProductModel->saveAll($result);
              // halt($depotBackProRes);
              if($depotBackProRes===FALSE){
                $this->orderModel->rollback();
                $this->depotBackModel->rollback();
                $this->error('增加退货商品表失败');
                exit;
              }

              // 4.修改商品库存
              $stockOrigin = $this->shopModel->whereIn('id',$pids)->column('stock');
              $num = count($stockOrigin);
              $newStock = [];
              for ($i=0; $i < $num; $i++) { 
                $newStock[] = $stockOrigin[$i]+$nums[$i];
              }
              $updateStockData = [];
              for ($i=0; $i < $num ; $i++) { 
                $updateStockData[] = [
                  'id'=>$pids[$i],
                  'stock'=>$newStock[$i],
                ];
              }
              $updateStockRes = $this->shopModel->isUpdate(true)->saveAll($updateStockData);
              // halt($updateStockRes);
              if($updateStockRes ===FALSE){
                $this->depotBackProductModel->rollback();
                $this->orderModel->rollback();
                $this->depotBackModel->rollback();
                $this->error('修改商品库存失败');
                exit;
              }

              // 5.修改用户的账户余额
              $orderMoney = $this->orderModel->where('code',$orderCode)->value('amount');
              $oldUserMoney =  $this->userModel->where('id',$uid)->value('money');
              $newUserMoney = $orderMoney+$oldUserMoney;
              // halt($newUserMoney);
              $upMoney = [
                'money'=>$newUserMoney
              ];
              $updateMoneyRes = $this->userModel->where('id',$uid)->update($upMoney);
              // halt($updateMoneyRes);
              if($updateMoneyRes === FALSE){
                $this->shopModel->rollback();
                $this->depotBackProductModel->rollback();
                $this->orderModel->rollback();
                $this->depotBackModel->rollback();
                $this->error('修改用户的账户余额失败');
                exit;
              }

              // 6.若有用优惠券，判断是否过了活动期限，是则不返回，否则返回
              $iscid = $this->orderModel->where('code',$orderCode)->value('cid');
              $endTime = $this->couponModel->where('id',$iscid)->value('endAt');
              $times = time();
              // halt($iscid);
              // 不为空
              if(!empty($iscid) && $endTime>$times){
                // halt($endTime);
                $whereCou = [
                  'busid'=>$uid,
                  'cid'=>$iscid,
                ];
                $updateCouRes = $this->couponReceiveModel->where($whereCou)->update(['type'=>0]);
                // halt($times);
                if($updateCouRes === FALSE){
                  $this->userModel->rollback();
                  $this->shopModel->rollback();
                  $this->depotBackProductModel->rollback();
                  $this->orderModel->rollback();
                  $this->depotBackModel->rollback();
                  $this->error('修改优惠券失败');
                  exit;
                }else{
                  $this->depotBackModel->commit();
                  $this->orderModel->commit();
                  $this->depotBackProductModel->commit();
                  $this->shopModel->commit();
                  $this->userModel->commit();
                  $this->couponReceiveModel->commit();
                  $this->success('申请退货成功');
                  exit;
                }
              }


              // halt($updateOStatusRes);
              if($updateOStatusRes===FALSE || $depotBackProRes===FALSE ||
              $updateStockRes ===FALSE || $updateMoneyRes === FALSE){
                $this->shopModel->rollback();
                $this->depotBackProductModel->rollback();
                $this->orderModel->rollback();
                $this->depotBackModel->rollback();
                $this->error('申请退货失败');
                exit;
              }else{
                $this->depotBackModel->commit();
                $this->orderModel->commit();
                $this->depotBackProductModel->commit();
                $this->shopModel->commit();
                $this->userModel->commit();
                $this->success('申请退货成功');
                exit;
              }
            }else{
              $this->error('该订单退货申请中...');
              exit;
            }
        }else{
          $this->error('用户非法');
          exit;
        }
      }
    }

    // 查看物流详情
    public function getExpressInfo(){
      if($this->request->isPost()){
        $code = config("site.code");
        // halt($code);
        $orderId  = $this->request->param('orderId');

        // 查询快递单号
        $expressCode = $this->orderModel->where('id', $orderId)->value('expresscode');
        if(!empty($expressCode)){
        error_reporting(E_ALL || ~E_NOTICE);
        $host = "https://wuliu.market.alicloudapi.com";//api访问链接
        $path = "/kdi";//API访问后缀
        $method = "GET";
        $appcode = "$code";//开通服务后 买家中心-查看AppCode
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "no=$expressCode";  //参数写在这里
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $out_put = curl_exec($curl);

        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        list($header, $body) = explode("\r\n\r\n", $out_put, 2);
        if ($httpCode == 200) {
            // print("正常请求计费(其他均不计费)<br>");
            // print($body);
            $expressData = $body;
        } else {
            if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
                print("参数错误");
            } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
                print("AppCode错误");
            } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
                print("请求的 Method、Path 或者环境错误");
            } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
                print("服务未被授权（或URL和Path不正确）");
            } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
                print("套餐包次数用完");
            } elseif ($httpCode == 403 && strpos($header, "Api Market Subscription quota exhausted") !== false) {
                print("套餐包次数用完，请续购套餐");
            } elseif ($httpCode == 500) {
                print("API网关错误");
            } elseif ($httpCode == 0) {
                print("URL错误");
            } else {
                print("参数名错误 或 其他错误");
                print($httpCode);
                $headers = explode("\r\n", $header);
                $headList = array();
                foreach ($headers as $head) {
                    $value = explode(':', $head);
                    $headList[$value[0]] = $value[1];
                }
                print($headList['x-ca-error-message']);
            }
        }
        $expressData=json_decode($expressData);
        // halt($expressData);
        $this->success('返回物流数据成功',null,$expressData);
        exit;

        }else{
          $this->error('快递单号为空');
          exit;
        }
        // halt($expressCode );
      }
    }

    // 在我的界面，获取订单信息
    public function getAboutOrder(){
      if($this->request->isPost()){
        $uid = (int)$this->request->param('uid');
        // halt($uid);
        $ordersData = $this->orderModel->where('busid',$uid)->select();
        $paied = [];
        $expressed = [];
        $Recipient = [];
        $reGoods = [];
        $noPay = [];
        $paiednum = 0;
        $expressednum = 0;
        $Recipientnum = 0;
        $reGoodsnum = 0;
        $noPaynum = 0;

        foreach($ordersData as $item){
          // halt($item['status']);
          // $status[] = $item['status'];
          // 已支付
          if($item['status']==1){
            $paied[] = $item['status'];
            $paiednum = count($paied);
          }
          // 已发货
          if($item['status']==2){
            $expressed[] = $item['status'];
            $expressednum = count($expressed);
          }
          // 已收货
          if($item['status']==3){
            $Recipient[] = $item['status'];
            $Recipientnum = count($Recipient);
          }
          // 退货
          if($item['status']==-1){
            $reGoods[] = $item['status'];
            $reGoodsnum = count($reGoods);
          } 
          // 未支付
          if($item['status']==-2){
            $noPay[] = $item['status'];
            $noPaynum = count($noPay);
          }
        }
        // halt($noPaynum);
        $OData = [
          'paiednum' => $paiednum,
          'expressednum' =>$expressednum,
          'Recipientnum' => $Recipientnum,
          'reGoodsnum' => $reGoodsnum,
          'noPaynum' => $noPaynum,
        ];
        $this->success('查询订单成功',null,$OData);
        exit;
      }
    }
}

?>

